package com.thundersoft.pickcolor.fragment;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.thundersoft.pickcolor.R;
import com.thundersoft.pickcolor.activity.CollectActivity;
import com.thundersoft.pickcolor.activity.ToolActivity;
import com.thundersoft.pickcolor.adapter.ColorAdapter;
import com.thundersoft.pickcolor.bean.Color;
import com.thundersoft.pickcolor.utils.UtilTools;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class FragmentHome extends Fragment {

    private View view;
    private Toolbar mToolbar;
    private List<Color> mColorList = new ArrayList<>();
    private Handler mHandler;
    private ColorAdapter mColorAdapter;
    private RecyclerView mRecyclerView;
    private RefreshLayout mRefreshLayout;
    private Context mContext;
    private GridLayoutManager mGridLayoutManager;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, null);
        mContext = view.getContext();
        mToolbar = view.findViewById(R.id.toolbar_home);
        mToolbar.setTitle(R.string.pick_color);
        mToolbar.setTitleTextColor(getResources().getColor(R.color.app_title_color));
        TextView textView = getToolbarTitleView((AppCompatActivity)getActivity(),mToolbar);
        if(textView != null){
            UtilTools.setFont(mContext,textView);
        }

        ((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
        ActionBar actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
        if(actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.pickcolor_small_icon);
        }

        setHasOptionsMenu(true);

        mHandler = new Handler();

        mRefreshLayout = view.findViewById(R.id.refresh_layout);
        mRecyclerView = view.findViewById(R.id.recycler_view);
        mGridLayoutManager = new GridLayoutManager
                (mContext,3,GridLayoutManager.VERTICAL,false);
        mRecyclerView.setLayoutManager(mGridLayoutManager);

        mColorAdapter = new ColorAdapter(mContext);
        mRecyclerView.setAdapter(mColorAdapter);

        //实现每一行不同布局
        mGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int i) {
                int type = mColorAdapter.getItemViewType(i);
                switch (type){
                    case Color.TYPE_ZERO:
                    case Color.TYPE_ONE:
                        return 3;
                    case Color.TYPE_TWO:
                        return 1;
                    default:
                        return 1;
                }
            }
        });
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mColorAdapter.clearList();
                        initData();
                        mRefreshLayout.finishRefresh();
                    }
                });
            }
        });

        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mRefreshLayout.finishLoadMore();

                    }
                });
            }
        });

        mRefreshLayout.setEnableLoadMore(true);
        mRefreshLayout.autoRefresh();

        initData();
        return view;
    }

    private void initData() {
        mColorList.clear();
        banner();
        query();
    }

    private void banner() {
        List<String> picPath = new ArrayList<>();
        picPath.add("http://bmob-cdn-23887.b0.upaiyun.com/2019/04/08/3f8c119d401b87d38013e7a833ea0dec.jpg");
        picPath.add("http://bmob-cdn-23887.b0.upaiyun.com/2019/04/08/cfd70554409c3da9803cf61255630e04.jpg");
        picPath.add("http://bmob-cdn-23887.b0.upaiyun.com/2019/04/08/4ab21cc340b98cab80a51389d18c9333.jpg");
        Color colorBanner = new Color(Color.TYPE_ZERO,picPath);
        mColorList.add(colorBanner);
    }

    private void query() {
        // 查询数据
        Uri uri = Uri.parse("content://com.thundersoft.pickcolor.provider/color");
        Cursor cursor = null;
        Cursor cursorKind ;
        Set hashSet = new HashSet();
        try {
            cursorKind = mContext.getContentResolver().query(uri,null,null,
                    null,null);
            // 获取所有的分类
            if(cursorKind !=null){
                hashSet.clear();
                while(cursorKind.moveToNext()){
                    String str = cursorKind.getString(cursorKind.getColumnIndex("kind"));
                    if((!str.equals(getString(R.string.search)))&&(!str.equals(mContext.getString(R.string.collect)))){
                        hashSet.add(str);
                    }
                }
            }
            // 遍历
            Iterator item = hashSet.iterator();
            while (item.hasNext()){
                String s = (String) item.next();
                cursor = mContext.getContentResolver().query(uri,null,
                        "kind = ? limit 6",new String[]{s},null);

                // 设置分类标题
                Color colorTitle = new Color(Color.TYPE_ONE,s);
                mColorList.add(colorTitle);

                // 设置类中的部分item
                if(cursor !=null){
                    while(cursor.moveToNext()){
                        int id = cursor.getInt(cursor.getColumnIndex("id"));
                        String hexValue = cursor.getString(cursor.getColumnIndex("hexValue"));
                        int rValue = cursor.getInt(cursor.getColumnIndex("rValue"));
                        int gValue = cursor.getInt(cursor.getColumnIndex("gValue"));
                        int bValue = cursor.getInt(cursor.getColumnIndex("bValue"));
                        String describe = cursor.getString(cursor.getColumnIndex("describe"));
                        Color color = new Color(id,Color.TYPE_TWO,rValue, gValue, bValue, hexValue, describe);
                        mColorList.add(color);
                    }
                }
            }
            mColorAdapter.addList(mColorList);
            mColorAdapter.notifyDataSetChanged();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(cursor !=null){
                cursor.close();
            }
        }
    }

    public static TextView getToolbarTitleView(AppCompatActivity activity, Toolbar toolbar){
        ActionBar actionBar = activity.getSupportActionBar();
        CharSequence actionbarTitle = null;
        if(actionBar != null)
            actionbarTitle = actionBar.getTitle();
        actionbarTitle = TextUtils.isEmpty(actionbarTitle) ? toolbar.getTitle() : actionbarTitle;
        if(TextUtils.isEmpty(actionbarTitle)) return null;

        // can't find if title not set
        for(int i= 0; i < toolbar.getChildCount(); i++){
            View v = toolbar.getChildAt(i);
            if(v != null && v instanceof TextView){
                TextView t = (TextView) v;
                CharSequence title = t.getText();
                if(!TextUtils.isEmpty(title) && actionbarTitle.equals(title)
                        && t.getId() == View.NO_ID){
                    return t;
                }
            }
        }
        return null;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        inflater.inflate(R.menu.home_toolbar_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int i = item.getItemId();
        if (i == R.id.home_icon_collect) {
            startActivity(new Intent(mContext,CollectActivity.class));
        } else if (i == R.id.home_icon_tool) {
            startActivity(new Intent(getActivity(),ToolActivity.class));
        }
        return true;
    }
}

